package cn.seaboot.admin.core.service;

import cn.seaboot.admin.core.bean.DynamicDictionary;
import cn.seaboot.admin.core.dao.DynamicDictionaryDao;
import cn.seaboot.commons.file.Beetles;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DynamicDictionaryService {

    @Resource
    private DynamicDictionaryDao dynamicDicDao;

    /**
     * 查询列表
     *
     * @param dicType 字典类型
     * @return 字典列表
     */
    public List<DynamicDictionary> queryBySort(int dicType) {
        return dynamicDicDao.selectByDicType(dicType);
    }

    /**
     * 查询为Map
     *
     * @param dicType 字典类型
     * @return Map
     */
    public Map<String, Object> queryAsMap(int dicType) {
        List<DynamicDictionary> l = this.queryBySort(dicType);
        Map<String, Object> map = new HashMap<>(l.size());
        for (DynamicDictionary d : l) {
            map.put(d.getDicKey(), d.getDicVal());
        }
        return map;
    }

    /**
     * 更新系统参数
     *
     * @param id     ID
     * @param dicVal 值
     * @return 是否成功
     * @throws IOException       模版引擎渲染异常
     */
    public int updateById(String id, String dicVal) throws IOException {
        DynamicDictionary old = dynamicDicDao.selectById(id);
        List<DynamicDictionary> list = this.queryBySort(old.getDicType());
        Map<String, Object> model = new HashMap<>(list.size() + 1);
        for (DynamicDictionary dic : list) {
            if (dic.getId().equals(id)) {
                dic.setDicVal(dicVal);
            }
            model.put(dic.getDicKey(), dic.getDicVal());
        }
        for (DynamicDictionary dic : list) {
            String desc = Beetles.process(dic.getDicTpl(), model);
            dic.setDicDesc(desc);
            dynamicDicDao.updateSampleById(dic);
        }
        return 1;
    }

    /**
     * 获取全部数据
     *
     * @return 列表
     */
    public List<DynamicDictionary> selectAll() {
        return dynamicDicDao.selectAll();
    }
}
